package org.tigris.atlas.quizme.client.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.tigris.atlas.quizme.client.form.LoginForm;
import org.tigris.atlas.quizme.client.utils.ClientUtils;
import org.tigris.atlas.quizme.client.utils.Constants;
import org.tigris.atlas.quizme.service.UserProfileServiceResponse;
import org.tigris.atlas.quizme.service.delegate.AuthenticateServiceDelegate;
import org.tigris.atlas.quizme.service.delegate.ServiceDelegateFactory;
import org.tigris.atlas.quizme.transfer.UserProfile;

/**
 * Log the user into the system.  This action accesses the business layer using
 * the "ServiceDelegatefactory" from atlas.  This abtracts the business layer 
 * so that struts does not need to know how to access the service.  It could be using
 * webservices, ejb or pojo implementation.
 * 
 * @author Robert Simmering
 */
public class LoginAction  extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
		      HttpServletRequest request, HttpServletResponse response) {	
		LoginForm loginForm = (LoginForm)form;
		
		// Obtain the atlas generated delegate
		AuthenticateServiceDelegate sd = ServiceDelegateFactory.createAuthenticateServiceDelegate();
		
		// use the delegate to call the authenticate method
		UserProfileServiceResponse upResponse = sd.authenticate(loginForm.getUserProfileUsername(), loginForm.getUserProfilePassword());
		if(upResponse.getMessages().hasErrorMessages() || upResponse.getUserProfile() == null){
			ClientUtils.getMessagesHandler().handleMessages( upResponse.getMessages(), loginForm.getClass(), request);
			return mapping.findForward("fail");
		}
		
		UserProfile user = upResponse.getUserProfile();
	    request.getSession().setAttribute(Constants.USER_KEY, user);
	   
		return mapping.findForward("success");
	}
}
